<?php
/**
 * 阿里云短信 无法自定义短信内容
 * 需额外传
 * sign_name  : 签名
 * template_code :模板code
 */

namespace app\service\SmsService;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\Config;

class AliSms extends Driver
{
    private static $instance;

    private $config = [
        'accessKeyId' => '',
        'accessKeySecret' => ''
    ];

    public function __construct(array $config = [])
    {
        if (isset($config['api_key'])) $this->config['accessKeyId'] = $config['api_key'];
        if (isset($config['api_secret'])) $this->config['accessKeySecret'] = $config['api_secret'];
    }

    static function instance(array $config = [])
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self($config);
        }
        return self::$instance;
    }


    public function sendSingle($mobile, $content, $params = [])
    {
        $res = $this->sendRequest($mobile, $content, $params);
        if ($res['status'] != STATUS_CODE_SUCCESS) {
            return $res;
        }
        return funReturn(STATUS_CODE_SUCCESS, 'success');
    }


    private function sendRequest($mobile, $content, $params = [])
    {

        $templateCode = $params['template_code'] ?? '';
        $signName = $params['sign_name'] ?? '';
        unset($params['mobile'], $params['content'], $params['template_code'], $params['sign_name'], $params['api_key']);
        $client = self::createClient($this->config['accessKeyId'], $this->config['accessKeySecret']);
        $data = [
            "signName" => $signName,
            "templateCode" => $templateCode,
            "phoneNumbers" => $mobile,
            "templateParam" => json_encode($params, JSON_UNESCAPED_UNICODE)
        ];

        $sendSmsRequest = new SendSmsRequest($data);
        $runtime = new RuntimeOptions([]);
        try {
            $res = $client->sendSmsWithOptions($sendSmsRequest, $runtime);
            $statusCode = $res->statusCode;
            $body = (array)$res->body;
            $code = $body['code'] ?? '';
            if ($code != 'OK') {
                return funReturn(STATUS_CODE_INSIDEERROR, '发送失败:' . $body['message'] ?? '发生未知错误');
            }
            return funReturn(STATUS_CODE_SUCCESS, '发送成功');
        } catch (\Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            return funReturn(STATUS_CODE_DATAERROR, '发送失败:' . $error->getMessage());
        }
    }

    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Dysmsapi Client
     */
    public static function createClient($accessKeyId, $accessKeySecret)
    {
        $config = new Config([
            // 您的 AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 您的 AccessKey Secret
            "accessKeySecret" => $accessKeySecret
        ]);
        // 访问的域名
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }
}